/* Copyright (c) 2004-2024 Peigen.info. All rights reserved. */

package info.peigen.hotpot.component.notice.service;

import cn.binarywang.wx.miniapp.api.WxMaMsgService;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import cn.hutool.core.util.ObjectUtil;
import info.peigen.hotpot.common.core.result.ResultStatus;
import info.peigen.hotpot.component.notice.facade.NoticeServiceFacade;
import info.peigen.hotpot.component.notice.facade.order.SimpleNoticeOrder;
import info.peigen.hotpot.component.notice.facade.order.TemplateNoticeOrder;
import info.peigen.hotpot.component.notice.facade.result.NoticeResult;
import info.peigen.hotpot.component.notice.order.WechatMiniappNoticeOrder;
import me.chanjar.weixin.common.error.WxErrorException;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <b>(WechatMiniappNoticeService)</b>
 *
 * @author LiDaHai
 * @version 1.0.0
 * @since 2022/9/22
 */
@Component
public class WechatMiniappNoticeService implements NoticeServiceFacade {
    @Inject
    WxMaService wxMaService;

    @Override
    public NoticeResult sendSimpleNotice(SimpleNoticeOrder order) {
        return null;
    }

    @Override
    public NoticeResult sendTemplateNotice(TemplateNoticeOrder order) {
        NoticeResult             result      = new NoticeResult();
        WechatMiniappNoticeOrder wechatOrder = (WechatMiniappNoticeOrder) order;
        try {
            List<WxMaSubscribeMessage.MsgData> data = wechatOrder.getParameters().entrySet().stream().map(entry -> {
                WxMaSubscribeMessage.MsgData msgData = new WxMaSubscribeMessage.MsgData();
                msgData.setName(entry.getKey());
                msgData.setValue(ObjectUtil.toString(entry.getValue()));
                return msgData;
            }).collect(Collectors.toList());
            WxMaMsgService wxMaMsgService = wxMaService.getMsgService();
            wxMaMsgService.sendSubscribeMsg(WxMaSubscribeMessage.builder()
                    .toUser(wechatOrder.getToUser()).page(wechatOrder.getPage())
                    .data(data).build());
            result.setStatus(ResultStatus.success);
        } catch (WxErrorException e) {
            e.printStackTrace();
            result.setStatus(ResultStatus.failure);
        }
        return result;
    }
}